﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ivony.Data;
using Ivony.Fluent;
using Ivony.Html;
using Ivony.Parser;
using Ivony.Html.Parser;
using System.Text.RegularExpressions;

namespace FriendAD.Core
{
   public class Spider
    {
        public static Article getArticle(string url)
        {
            var html = getHtmlDom(url);
            Article mod = new Article()
            {
                Title = html.FindFirst("h2").InnerText(),
                Context = html.FindFirst(".rich_media_content").InnerHtml(),
                wechat=html.FindFirst(".rich_media_meta_list").InnerHtml()
            };
            string[] vids = mod.Context.Split(new string[] { "vid=" },StringSplitOptions.RemoveEmptyEntries); // mod.Context.Split("vid=",StringSplitOptions.RemoveEmptyEntries);

            mod.Context = Regex.Replace(mod.Context, @"/<(\/?i?frame.*?)>/si", string.Empty);
            if (vids.Length>1)
            {
                vids = Regex.Split(vids[1], "&");
                mod.Context = string.Format("<p><iframe height=300 width=100% src=\"http://v.qq.com/iframe/player.html?vid={0}\" frameborder=0 allowfullscreen></iframe></p>", vids[0]) + mod.Context;
            }
            //图片地址替换
            mod.Context = mod.Context.Replace("data-src", "src");
            return mod;
        }

       

        /// <summary>
        /// 文章列表获取 
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static List<ArticleInfo> getArticleList(string url)
        {
            List<ArticleInfo> list = new List<ArticleInfo>();

            var p = getHtmlDom(url);
            
            foreach (IHtmlElement item in p.Find(".wx-news-info2"))
            {
                ArticleInfo mod = new ArticleInfo()
                {
                    Title = item.FindFirst("h4").InnerText(),
                    Url = item.FindFirst("a").Attribute("href").AttributeValue,
                    Count = item.FindFirst(".s-p").InnerText().Trim().Substring(55)
                };
                list.Add(mod);
            }
            
            return list;
        }
        /// <summary>
        /// 获取页面对象
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private static IHtmlDocument getHtmlDom(string url)
        {
            return new JumonyParser().LoadDocument(url, Encoding.UTF8);
        }
    }
    public class ArticleInfo
    {
        public string Title { set; get; }
        public string Url { set; get; }
        public string Count { set; get; }
    }
}
